﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace WpfDataStreamDemo.Utility
{
    internal static class Extensions
    {
        private static readonly ManualResetEvent _mre;

        static Extensions()
        {
            _mre = new ManualResetEvent(true);
        }

        public static void Pause()
        {
            _mre.Reset();
        }

        public static void Continue()
        {
            _mre.Set();
        }

        public static void AddOnUi<T>(this ICollection<T> collection, T item)
        {
            Action<T> addMethod = collection.Add;
            if (Application.Current != null)
                Application.Current.Dispatcher.Invoke(addMethod, item);
        }

        public static void RunOnUi<T>(this ICollection<T> collection, Action action)
        {
            if (Application.Current != null)
                Application.Current.Dispatcher.Invoke(DispatcherPriority.DataBind, action);
        }

        public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
        {
            foreach (var item in enumeration)
            {
                action(item);
                Thread.Sleep(1); //give some processor time for other ui operations
                _mre.WaitOne();
            }
        }

        public static IEnumerable<T> Select<T>(this IDataReader reader,
                                               Func<IDataReader, T> projection)
        {
            while (reader.Read())
            {
                yield return projection(reader);
            }
        }

    }
}
